package com.zsd.android.common

import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment

abstract class BaseFragment<V : IBaseView, M : BaseModel<*>, P : BasePresenter<V, M>>: Fragment() {

    protected var mContext: Activity? = null
    protected var mPresenter: P? = null
    protected var containerView: View? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mContext = activity
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        containerView = inflater.inflate(layoutId(), container, false)
        return containerView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mPresenter = initPresenter()
        initView(savedInstanceState)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mPresenter?.destroy()
    }

    /**
     * 显示toast
     *
     * @param msg 显示内容
     */
    protected fun showToast(msg: String?) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show()
    }

    /**
     * 显示View
     *
     * @param view 要显示的View
     */
    protected fun showView(view: View) {
        if (!view.isVisible) {
            view.visibility = View.VISIBLE
        }
    }

    /**
     * 隐藏view
     *
     * @param view 要隐藏的View
     * @param visibility 隐藏方式，默认是GONE，也可以是INVISIBILITY
     */
    protected fun hideView(view: View, visibility: Int = View.GONE) {
        if (view.isVisible) {
            view.visibility = visibility
        }
    }

    protected abstract fun layoutId(): Int

    protected abstract fun initPresenter(): P?

    protected abstract fun initView(savedInstanceState: Bundle?)
}